import { message } from "ant-design-vue";

export default class ErrorCatcher {
  customErrorHandler;

  constructor(customErrorHandler) {
    this.customErrorHandler = customErrorHandler;
  }

  start() {
    window.addEventListener("error", this.errorHandler);
    window.addEventListener("unhandledrejection", this.errorHandler);
  }

  stop() {
    window.removeEventListener("error", this.errorHandler);
    window.removeEventListener("unhandledrejection", this.errorHandler);
  }

  errorHandler(event) {
    if (this.customErrorHandler) {
      this.customErrorHandler(event);
    } else {
      console.log(event.reason, event.data, event.error);
      if (typeof event === "string") {
        message.error(event);
      } else if (event.reason) {
        message.error(event.reason.message || event.reason.msg || event.reason);
      } else if (event.error) {
        message.error(event.error.message || event.error.msg);
      }
    }
  }
}
